<template>
  <a-drawer
    :width="340"
    :mask-closable="false"
    :visible="visible"
    unmount-on-close
    :ok-loading="loading"
    @ok="onOk"
    @cancel="close">
    <template #title>
      {{ title }}
    </template>
    <div>
      <a-form
        ref="form"
        layout="vertical"
        :model="form"
        :disabled="disabled"
        :style="{width:'100%'}">
        <a-form-item
          field="title"
          label="资源名称"
          :rules="[{required: true, message:'请输入资源名称'}]">
          <a-input v-model="form.title" placeholder="请输入资源名称..." allow-clear />
        </a-form-item>
        <a-form-item
          field="name"
          label="资源编码"
          :rules="[{required: true, message:'请输入资源编码'}]">
          <a-input v-model="form.name" placeholder="请输入资源编码..." allow-clear />
        </a-form-item>
        <a-form-item
          field="type"
          label="资源类型"
          :rules="[{required: true, message:'请选择资源类型'}]">
          <a-radio-group v-model="form.type" type="button">
            <a-radio :value="0">菜单</a-radio>
            <a-radio :value="1">权限</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item
          v-if="!form.type"
          field="path"
          label="路由">
          <a-input v-model="form.path" placeholder="请输入路由地址..." allow-clear />
        </a-form-item>
        <a-form-item
          v-if="!form.type"
          field="component"
          label="组件路径">
          <a-select v-model="form.component" placeholder="请输入组件路径..." allow-create allow-clear>
            <a-option value="/layout/default-layout.vue">/layout/default-layout.vue</a-option>
          </a-select>
        </a-form-item>
        <a-form-item
          v-if="!form.type"
          field="redirect"
          label="重定向">
          <a-input v-model="form.redirect" placeholder="请输入重定向地址..." allow-clear />
        </a-form-item>
        <a-form-item
          field="order"
          label="排序">
          <a-input-number v-model="form.order" placeholder="请输入排序..." allow-clear />
        </a-form-item>
        <a-form-item
          v-if="!form.type"
          field="icon"
          label="图标">
          <a-input v-model="form.icon" placeholder="请输入图标..." allow-clear />
        </a-form-item>
        <a-form-item v-if="!form.type" field="enabled" label="缓存">
          <a-switch
            v-model:model-value="form.cache"
            type="round"
            :checked-value="true"
            :unchecked-value="false"
            unchecked-color="#F53F3F"
          >
            <template #checked>
              开启
            </template>
            <template #unchecked>
              关闭
            </template>
          </a-switch>
        </a-form-item>
        <a-form-item v-if="!form.type" field="enabled" label="标签页">
          <a-switch
            v-model:model-value="form.affix"
            type="round"
            :checked-value="true"
            :unchecked-value="false"
            unchecked-color="#F53F3F"
          >
            <template #checked>
              开启
            </template>
            <template #unchecked>
              关闭
            </template>
          </a-switch>
        </a-form-item>
        <a-form-item v-if="!form.type" field="enabled" label="隐藏左侧菜单">
          <a-switch
            v-model:model-value="form.hidden"
            type="round"
            :checked-value="true"
            :unchecked-value="false"
            unchecked-color="#F53F3F"
          >
            <template #checked>
              是
            </template>
            <template #unchecked>
              否
            </template>
          </a-switch>
        </a-form-item>
        <a-form-item
          field="parentId"
          label="上级项">
          <a-tree-select
            v-model="form.parentId"
            :allow-clear="true"
            :data="authorities"
            :field-names="{
                key: 'id'
            }"
            tree-check-strictly
            placeholder="请选择上级资源..."
          ></a-tree-select>

        </a-form-item>
      </a-form>
    </div>
  </a-drawer>
</template>

<script>

import useLoading from "@/hooks/loading";
import {Operation} from "@/types/global";
import {create, findById, listTree, update} from "@/api/modules/system/authority";
import {disableNode} from "@/utils/tree-utils";

const { loading, setLoading } = useLoading()
export default {
  name: 'AuthorityBoard',
emits: ['ok'],
  data() {
    return {
      visible: false,
      loading,
      title: '',
      disabled: false,
      form: {
        type: 1,
        parentId: 0
      },
      type: '',
      authorities: [{id: 0, title: '无上级项', meta: {}}]
    }
  },
  methods: {
    async open(id, type) {
      if (id) {
        const { data: tree } = await listTree()
        this.authorities = [...this.authorities, ...tree]
        disableNode(id, this.authorities)
        const { data } = await findById(id)
        this.form = {
          ...data,
          ...data.meta
        }
      }
      this.disabled = this.type === Operation.PREVIEW
      this.title = type
      this.type = type
      this.visible = true
    },
    close() {
      this.visible = false
      this.title = ''
      this.disabled = false
      this.form = {
        type: 1,
        parentId: 0
      }
      this.authorities = [{id: 0, title: '无上级项', meta: {}}]
    },
    onOk() {
      if (this.type === Operation.PREVIEW) {
        this.close()
        return
      }
      this.$refs.form.validate(async errors => {
        if (!errors) {
          try {
            setLoading(true)
            delete this.form.meta
            delete this.form.children
            if (this.type === Operation.CREATE) {
              await create(this.form)
            } else  {
              await update(this.form)
            }
            this.close()
            this.$emit('ok')
          } finally {
            setLoading(false)
          }
        }
      })
    },
  }
}

// const authorityDrawerForm = ref<any>()
// const authorities = ref<AuthorityVo[]>()
// const formData = ref<AuthorityDto>(defaultFormData());
// const { dataModel, openModel, closeModel } = useDataModel();
// const { loading, setLoading } = useLoading();
// const emit = defineEmits(["refresh"]);
//
// const createHandle = async () => {
//   openModel("添加资源信息", false, true, Operation.CREATE);
//   authorities.value = [{id: 0, title: '无上级项', meta: {}}, ...((await treeList()).data  || [])]
// };
//
// const updateHandle = async (id: number) => {
//   authorities.value = [{id: 0, title: '无上级项', meta: {}}, ...((await treeList()).data  || [])]
//     const { data: authorityVo } = await findById(id)
//   disableNode(id, authorities.value)
//   const { name, title, parentId, order, component, type, path, redirect } = authorityVo
//   formData.value = {
//       id, name, title, parentId, order, component, type, path, redirect,
//       ...authorityVo.meta
//   }
//   openModel("编辑资源信息", false, true, Operation.UPDATE);
// }
//
// const previewHandle = async (id: number) => {
//   authorities.value = [{id: 0, title: '无上级项', meta: {}}, ...((await treeList()).data || [])]
//   const { data: authorityVo } = await findById(id)
//   if (!authorityVo) {
//     Message.error({
//       content: "数据不存在",
//       duration: 2000
//     });
//   }
//   const { name, title, parentId, order, component, type, path, redirect } = authorityVo
//   formData.value = {
//     id, name, title, parentId, order, component, type, path, redirect,
//     ...authorityVo.meta
//   }
//   openModel("预览资源信息", true, false, Operation.PREVIEW);
// }
//
// const handleCancel = () => {
//   closeModel();
//   formData.value = defaultFormData()
//   setLoading(false);
// };
//
// const handleOk = async () => {
//   if (dataModel.submit) {
//     setLoading(true);
//     if (authorityDrawerForm.value) {
//       authorityDrawerForm.value?.validate(async (errors: undefined | Record<string, ValidatedError>) => {
//         if(!errors) {
//           try {
//             if (dataModel.type === Operation.CREATE) {
//               await create(formData.value);
//               Message.success({
//                 content: "添加成功",
//                 duration: 2000
//               });
//             } else {
//               await update(formData.value);
//               Message.success({
//                 content: "修改成功",
//                 duration: 2000
//               });
//             }
//           } finally {
//             handleCancel();
//           }
//           emit("refresh");
//         } else {
//           setTimeout(() => {
//             setLoading(false);
//           }, 1000);
//         }
//       });
//     }
//   }
// }
//
// defineExpose({ createHandle, updateHandle, previewHandle });
</script>

<style scoped>

</style>
